import config from "../config.js"

let timeout = 10000

const baseConfig = {
	baseUrl: config.baseUrl
}

const request = config => {

	// get请求映射params参数
	if (config.params) {
		config.url = config.url + '?' + tansParams(config.params)
	}

	console.log("请求地址：" + (config.baseUrl || baseConfig.baseUrl) + config.url);
	let tk = uni.getStorageSync("token");
	console.log("--------------------",tk)
	// let tk = localStorage.getItem("token");
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseConfig.baseUrl + config.url,
				data: config.data || {},
				header: {
					"Token": tk,
					'Content-Type': 'application/json'
				},
				dataType: 'json'
			}).then(response => {

				console.log("原始响应：", response);
				console.log("原始响应：", response.data.code);
				const res = response.data

				// 200 请求成功  
				// 403 权限不足 
				// 400 格式错误
				// 500 服务器错误

				switch (response.data.code) {

					case 200:
						resolve(res)
						break;

						// 参数错误
					case 401:
						toast(res.message)
						reject(res)
						break;

						// 权限不足
					case 400:
						toast("暂无该权限，请联系管理员")
						reject(res)
						break;

						// 登录过期
					case 203 || 202:
						// 记录token失效
						uni.setStorageSync("TOKEN_EXPIRE", true)
						toast("登录已过期，请重新登录...")
						
						uni.navigateTo({
							url: "/pages/login/login"
						})
						reject(res)
						break;

						// 服务内部错误
					case 9999:
						toast("服务器内部错误，请联系管理员")
						reject(res)
						break;

						// 处理未知错误
					default:
						break;
				}
				resolve(res)
			})
			.catch(error => {
				console.log("捕获到错误", error);
				let {
					message,
					errMsg
				} = error

				// request:fail timeout
				if (errMsg.includes("fail timeout") || errMsg.includes("time out")) {
					toast("请求超时")
				}

				console.log("catch message: ", message);
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast(message)
			})
	})
}

export default request

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + "="
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + "="
						result += subPart + encodeURIComponent(value[key]) + "&"
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&"
			}
		}
	}
	return result
}


// 提示
function toast(msg) {
	uni.showToast({
		title: msg,
		icon: "none",
		position: "top"
	})
}